package com.tour.controller;

import com.tour.bean.BaseParam;
import com.tour.bean.Hotel;
import com.tour.bean.ScenicSpot;
import com.tour.service.HotelService;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName HotelManageController
 * @Author 张梦兴
 * @Date 2020/3/16 21:52
 * @describe
 * 酒店后台管理
 */
@RestController
@RequestMapping("admin")
public class HotelManageController {

    private Logger log=Logger.getLogger(HotelManageController.class);
    @Autowired
    private HotelService service;

    /**
     * 修改是否推荐
     * @param
     * @return
     */
    @RequestMapping("/hotelManage/update/isRecommend/{is}/{id}")
    public Object update(@PathVariable("is") String is, @PathVariable("id") int id){
        String i="f".equals(is) ? "0" : "1";
        Hotel hotel=new Hotel();
        hotel.setId(id);
        hotel.setIsRecommend(i);
        return service.update(hotel);
    }

    @RequestMapping("/hotelMangage/delete/{id}")
    public Object delete(@PathVariable("id") int id){
        return service.delete(id);
    }


    @RequestMapping("/hotelMangage/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request)  {
        try {
            //获取文件名 : file.getOriginalFilename();
            String fileName = file.getOriginalFilename();
            String id=request.getParameter("file_id");
            switch (id){
                case "0": id="hotel_cover";break;
                case "1": id="hotel_address";break;
                case "2": id="hotel_contentOne";break;
                case "3": id="hotel_contentTwo";break;
                default:break;
            }
            String suffix=fileName.substring(fileName.lastIndexOf("."));
            long s = System.currentTimeMillis();
            fileName=id+"_"+s+suffix;

            //如果文件名为空，直接回到首页！
            if ("".equals(fileName)){
                return "error";
            }
            System.out.println("上传文件名 : "+fileName);

            //上传路径保存设置
            String path = request.getServletContext().getRealPath("/assets/upload");
            //如果路径不存在，创建一个
            File realPath = new File(path);
            if (!realPath.exists()){
                realPath.mkdir();
            }
            System.out.println("上传文件保存地址："+realPath);

            InputStream is = file.getInputStream(); //文件输入流
            OutputStream os = new FileOutputStream(new File(realPath,fileName)); //文件输出流

            //读取写出
            int len=0;
            byte[] buffer = new byte[1024];
            while ((len=is.read(buffer))!=-1){
                os.write(buffer,0,len);
                os.flush();
            }
            os.close();
            is.close();
            return fileName;
        }catch (Exception e){
            log.debug(e);
            return "error";
        }

    }

    @RequestMapping("/hotelMangage/insert")
    public String insert(BaseParam param){
        Hotel h=getHotel(param);
        log.debug(h);
        service.insert(h);
        return "success";
    }

    private Hotel getHotel(BaseParam param){
        Hotel ss=new Hotel();
        JSONObject json = param.getParamJson();
        ss.setMainTitle(json.getString("mainTitle"));
        ss.setSubTitle(json.getString("subTitle"));
        ss.setSynopsis(json.getString("synopsis"));
        Date date = new Date();
        SimpleDateFormat sd=new SimpleDateFormat("yyyy年MM月dd日");
        ss.setCurrDate(sd.format(date));
        ss.setTitleOne(json.getString("titleOne"));
        ss.setTitleOneDetail(json.getString("titleOneDetail"));
        ss.setTitleTwo(json.getString("titleTwo"));
        ss.setTitleTwoDetail(json.getString("titleTwoDetail"));
        ss.setTitleThree(json.getString("titleThree"));
        ss.setTitleThreeDetail(json.getString("titleThreeDetail"));
        ss.setAddress(json.getString("address"));
        ss.setPhone(json.getString("phone"));
        ss.setStar(json.getString("star"));
        ss.setNearbyScenic(json.getString("nearbyScenic"));
        ss.setRoute(json.getString("route"));
        ss.setPrice(Integer.parseInt(json.getString("price")));
        ss.setDescr(json.getString("descr"));
        ss.setIsRecommend("0");
        JSONArray imgNames = json.getJSONArray("imgNames");
        log.debug(imgNames);
        String prefix="assets/upload/";
        for(int i = 0; i < imgNames.length(); i++) {
            String name=imgNames.getString(i);
            if(name.contains("cover")){
                ss.setCoverPic(prefix+name);
            }
            if(name.contains("address")){
                ss.setAddressPic(prefix+name);
            }
            if (name.contains("contentOne")){
                ss.setContentPicOne(prefix+name);
            }
            if(name.contains("contentTwo")){
                ss.setContentPicTwo(prefix+name);
            }
        }
        return ss;
    }
}
